import VisualMenuButton from '@/components/visual-menu-button'
import MapCenter from '@/components/map-center'

export default {
  components: { MapCenter, VisualMenuButton },
  data () {
    return {
      enterpriseLists: [],
    }
  },
  computed: {
    enterpriseList () {
      return this.$store.state.energyEnterpriseList
    },
  },
  mounted () {
    this.$store.dispatch('GET_ENTERPRISE_LIST')
    this.$store.dispatch('GET_ENTERPRISE_MAP_LIST')

    const callback = (result) => {
      this.enterpriseLists = result
      setTimeout(() => {
        this.start()
      }, 20)
    }
    this.enterpriseListsWaterExpOrFn(callback)

    this.$watch(
      this.enterpriseListsWaterExpOrFn,
      callback
    )
  },
  methods: {
    enterpriseListsWaterExpOrFn (callback) {
      const enterpriseList = this.enterpriseList
      const enterpriseMapList = this.$store.state.enterpriseMapList
      const result = enterpriseList.map(v => ({ ...v }))
      result.forEach(v => {
        const id = v.enterpriseId || v.id || v.value
        const target = enterpriseMapList.find(vv => String(vv.enterpriseId) === String(id))
        if (target) {
          Object.assign(v, target)
        }
      })

      typeof callback === 'function' && callback(result)
      return result
    },
    start () {
      const wrap = this.$refs.wrap
      if (!wrap) return
      const parent = wrap.parentNode
      const clientHeight = parent.scrollHeight
      const scrollWidth = wrap.scrollHeight
      wrap.style.transform = 'translateY(0)'
      if (scrollWidth > clientHeight) {
        this.enterpriseLists = [
          ...this.enterpriseLists,
          ...this.enterpriseLists,
        ]

        this.$nextTick(() => {
          this.animate(scrollWidth, 15, (d) => {
            wrap.style.transform = `translateY(${-d}px)`
          })
        })
      }
    },
    animate (scrollWidth, speed = 10, move) {
      let arrive = false

      const s = scrollWidth
      // px/s
      const v = speed / 1000
      const t = s / v

      let startTime = performance.now()
      let passTime = 0

      const step = (timeStamp) => {
        passTime = timeStamp - startTime
        let d = v * passTime
        if (passTime >= t) {
          startTime = timeStamp
          arrive = true
          move && move(0, arrive)
        } else {
          if (d > s) d = s
          move && move(d, arrive)
        }
        requestAnimationFrame(step)
      }
      requestAnimationFrame(step)
    },
    getUnitName (type) {
      const energyUnits = this.$store.state.energyUnits
      const target = energyUnits.find(v => v.key === type)
      return target ? target.value : '吨标准煤'
    },
  }
}
